using System.Collections.Generic;
using System.IO;
using System.Text;
using Game.Framework;
using UnityEditor;
using UnityEngine;
using YooAsset;
using YooAsset.Editor;

namespace Game.Expand
{
    public class Automation : Editor
    {
        
        [MenuItem("ConfigMake/CreateAssetConfig", false, 4)]
        private static void CreateAssetConfig()
        {
            CreateAsset<AssetConfig>(AssetConfig.AssetConfigPath);
        }
        
        public static void CreateAsset<T>(string path) where T : ScriptableObject
        {
            var folder = Path.GetDirectoryName(Application.dataPath + "/Resources/" + path);
            if (!Directory.Exists(folder))
                Directory.CreateDirectory(folder);

            if (!Directory.Exists(folder + ".asset"))
            {
                T ac = CreateInstance<T>();
                AssetDatabase.CreateAsset(ac, "Assets/Resources/" + path + ".asset");
            }
        }
        
        [MenuItem("Tools/Copy InitialAssets To StreamingAssets", false, 3)]
        private static void CopyInitialAssetsToWorkSpace()
        {
            // 加载构建成功的资源清单对象
            byte[] manifestBytes = FileUtility.ReadAllBytes(PathUtils.BuildManifestPath);
            PackageManifest manifest = ManifestTools.DeserializeFromBinary(manifestBytes);

            List<string> assetPathList = new List<string>(); 
            for (int i = 0; i < manifest.AssetList.Count; i++)
            {
                var bundle = manifest.AssetList[i];
                if (bundle.AssetTags[0] == AssetConfig.Instance.AssetsTags[0])
                {
                    assetPathList.Add(bundle.AssetPath);
                }
            }
            
            // 查找所有需要打进首包资源的依赖AB
            HashSet<PackageBundle> bundles = new HashSet<PackageBundle>();
            foreach(var assetPath in assetPathList)
            {
                if(manifest.TryGetPackageAsset(assetPath, out PackageAsset packageAsset))
                {
                    var packageBundle = manifest.BundleList[packageAsset.BundleID];
                    if (bundles.Contains(packageBundle) == false)
                    {
                        bundles.Add(packageBundle);
                        for (int i = 0; i < packageBundle.DependIDs.Length; i++)
                        {
                            int depandsId = packageBundle.DependIDs[i];
                            var dependBundle = manifest.BundleList[depandsId];
                            if (bundles.Contains(dependBundle) == false)
                            {
                                bundles.Add(dependBundle);
                            }
                        }
                    }
                }
            }

            if(Directory.Exists(PathUtils.StreamingAssetsPath_PackageName))
                Directory.Delete(PathUtils.StreamingAssetsPath_PackageName, true);
            
            if (!Directory.Exists(PathUtils.StreamingAssetsPath_PackageName))
                Directory.CreateDirectory(PathUtils.StreamingAssetsPath_PackageName);
            
            //拷贝bundle文件
            foreach (var packageBundle in bundles)
            {
                string srcPath = $"{PathUtils.BuildAssetPath}/{packageBundle.FileName}";
                string destPath = $"{PathUtils.StreamingAssetsPath_PackageName}/{packageBundle.FileName}";
                
                PathUtils.CreateDirectory(destPath);
                File.Copy(srcPath, destPath);
            }

            //拷贝Manifest文件
            for (int i = 0; i < PathUtils.BuildVersionSuffix.Length; i++)
            {
                string srcPath = $"{PathUtils.BuildAssetPath}/{PathUtils.BuildVersionFileName + PathUtils.BuildVersionSuffix[i]}";
                string destPath = $"{PathUtils.StreamingAssetsPath_PackageName}/{PathUtils.BuildVersionFileName + PathUtils.BuildVersionSuffix[i]}";
                
                PathUtils.CreateDirectory(destPath);
                File.Copy(srcPath, destPath);
            }

            {
                string srcPath = $"{PathUtils.BuildAssetPath}/PackageManifest_{AssetConfig.Instance.PackageName}.version";
                string destPath = $"{PathUtils.StreamingAssetsPath_PackageName}/PackageManifest_{AssetConfig.Instance.PackageName}.version";
                
                PathUtils.CreateDirectory(destPath);
                File.Copy(srcPath, destPath);
            }
            
        }
        
        
        [MenuItem("Tools/SpriteAtlas/生成AtlasConfig")]
        public static void CreateAtlasConfig()
        {
            AtlasConfigController asset = CreateInstance<AtlasConfigController>();
            
            // asset.ParseAtlasPath("/AssetsPackage");
            asset.ParseAtlasPath("");
            
            AssetDatabase.CreateAsset(asset, "Assets/Resources/Settings/AtlasConfigController.asset");
            AssetDatabase.SaveAssets();

            EditorUtility.FocusProjectWindow();

            Selection.activeObject = asset;
        }
        
        [MenuItem("Tools/复制元数据")]
        public static void CopyDll()
        {
            var platForm = "Android";
#if UNITY_IOS
            platForm = "iOS";
#endif

            var sourcePath = $"{Application.dataPath}/../HybridCLRData/HotUpdateDlls/{platForm}/";
            var targetPath = $"{Application.dataPath}/AssetsPackage/HotUpdate/";

            //Dll
            Copy($"Game.Runtime", sourcePath);
            foreach (var fileName in DllLoader.dlls) Copy($"{fileName}", sourcePath);

            //补充元数据
            sourcePath = $"{Application.dataPath}/../HybridCLRData/AssembliesPostIl2CppStrip/{platForm}/";
            foreach (var fileName in AOTGenericReferences.PatchedAOTAssemblyList) Copy(fileName, sourcePath);

            void Copy(string fileName, string sourceDir)
            {
                fileName = fileName.Replace(".dll", "");
                var sourceFile = $"{sourceDir}{fileName}.dll";
                var dic = $"{targetPath}";
                // AssetDatabase.CreateFolder("Assets/AssetsPackage/HotUpdate", fileName);
                var targetFile = $"{dic}/{fileName}.bytes";
                File.Copy(sourceFile, targetFile, true);
            }

            AssetDatabase.Refresh();
        }
    }
}


